package com.sanerzone.smscenter.modules.sms.task;

import com.sanerzone.common.support.sequence.MsgId;
import com.sanerzone.smscenter.biz.cache.AccountCacheHelper;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSREQMessage;
import com.sanerzone.smscenter.biz.utils.SignHelper;
import com.sanerzone.smscenter.biz.utils.StringHelper;
import com.sanerzone.smscenter.common.utils.MQHelper;
import com.sanerzone.smscenter.modules.sms.entity.SmsSend;
import com.sanerzone.smscenter.modules.sms.service.SmsSendService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 定时短信的发送
 */
@Service
@Lazy(false)
public class TimingSendTask {
    @Autowired
    public MQHelper mQUtils;

    //定义5分钟以内的短信要发送
    private final int INMINUTES=5;


    private static Logger logger = LoggerFactory.getLogger(TimingSendTask.class);
    @Autowired
    private SmsSendService smsSendService;
    //每5分钟执行一次
    @Scheduled(cron = "0 0 1 * * ?")
    @Transactional(readOnly = false)
    public void run(){
        SimpleDateFormat sdf = new SimpleDateFormat("dd");
        SimpleDateFormat sdf2=new SimpleDateFormat( "MMddHHmm" );
        Date date = new Date();
        String formatDate = sdf.format(date);
        int day=Integer.parseInt( formatDate );
        String tableName="sms_send_"+day;

        List<SmsSend> smsSends=smsSendService.getAllTimingSmsSends(tableName);
        if (smsSends.size()==0){
            return;
        }
        int index=0;
        List<SmsSend> toSend=new ArrayList<>( );
        for (int i=0;i<smsSends.size();i++){
            SmsSend smsSend = smsSends.get( i );
            Date sendDate=smsSend.getSendTime();
            Date now = new Date( );
            String sendStr=sdf2.format( sendDate );
            String nowStr=sdf2.format( now );
            int sendInt=Integer.parseInt( sendStr );
            int nowInt=Integer.parseInt( nowStr );
            if (Math.abs(sendInt-nowInt)<=INMINUTES){
               SMSMTMessage smsmtMessage=transferToMts( smsSend );
                String msgId=mQUtils.sendSmsMT( smsmtMessage.getId(),smsmtMessage );
                if (msgId!=null){
                    index++;
                    //设置成失效
                    smsSendService.setFalse( tableName,smsSend.getId() );
                }
            }
        }
        logger.info( "定时任务执行完成,本次发送{}条短信",index );


    }

    public SMSMTMessage transferToMts(SmsSend temp) {

        SMSREQMessage message = new SMSREQMessage();

        message.setTaskid( temp.getTaskid() );
        message.setAccId( temp.getAccId() );
        message.setUserid( temp.getUserid() );
        message.setFeeType( AccountCacheHelper.getStringValue( temp.getUserid() + "_0", "feeType", "1" ) );
        message.setFeePayment( "1" );//默认值
        message.setCustomTaskid( temp.getCustomTaskid() );
        message.setCustomServiceid( "0" );
        message.setPhones( temp.getPhone() );
        message.setMsgContent( temp.getSmsContent() );
        message.setSmsContentId( temp.getSmsContentId() );
        message.setSmsType( "0" );//短信
        message.setSourceGateWayId( "HTTP" );
        message.setSourceGateWayProto( "HTTP" );
        message.setMassFlag( "0" );//单个发送
        message.setSendTime( temp.getSendTime() );
        message.setReceiveTime( temp.getReceiveTime() );
        message.setParamValue( temp.getParamValue() );
        message.setRegisteredDelivery(
                StringHelper.registeredDelivery( AccountCacheHelper.getStringValue( temp.getUserid() + "_" + temp.getAccId(), "callbackUrl", "" ) ) ? "1" : "0" );
        message.setDeliveryGateWayId( "HTTP" );
        message.setCustomServiceid( temp.getCustomServiceid() );
        SMSMTMessage entity;
        String content = message.getMsgContent();//短信内容
        entity = new SMSMTMessage();
        entity.setSmsREQMessage( message );
        entity.getSmsREQMessage().setPhones( "" );//把req的phones设置成空串
        entity.setId( new MsgId().toString() );//ID
        entity.setContentType( "0" );//内容类型 默认 0   0是什么意思？
        entity.setSmsContent( content );//短信内容
        entity.setSmsSize( StringHelper.smsSize( content ) );//短信长度
        entity.setPhone( temp.getPhone() );
        entity.setSmsContentSign( SignHelper.get( content ) );//短信签名
        entity.setServiceId( message.getCustomServiceid() ); //默认业务
        entity.setSendStatus( "T000" );
        entity.setShowLevel( 2 );
        entity.setNeedSplit( 1 );
        entity.setIsEffective( 1 );
        entity.setSendTime( temp.getSendTime() );
        //设置好网关属性
        entity.setGatewayId( temp.getGatewayId() );
        entity.setGatewayGroup( temp.getGatewayGroup() );
        entity.setSpnumber( temp.getSpnumber() );
        entity.setSubmitTime( new Date( ) );

        return entity;
    }



}

//封装成Mt

